package com.example.mangroves.scheduler;

/**
 * scheduler - 存放定时任务类，用于执行定时或周期性任务。这个定时任务每5秒钟请求一次你的模拟API，并打印响应。
 * 它可以看作是服务层的一部分，因为它负责按计划执行数据获取任务。它可以调用服务层的方法，但在许多情况下直接进行数据操作也是可行的。
 */

import com.example.mangroves.entity.EddyCovarianceData;
import com.example.mangroves.entity.GeoDetails;
import com.example.mangroves.entity.GeoInfo;
import com.example.mangroves.mapper.GeoTypeMapper;
import com.example.mangroves.service.impl.GeoDetailServiceImpl;
import com.example.mangroves.service.impl.GeoInfoServiceImpl;
import com.example.mangroves.service.impl.GeoTypeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.List;

//“监听”接口
@Component
@Configurable
public class DataFetchScheduler {
    private final RestTemplate restTemplate = new RestTemplate();

    private static final Logger log = LoggerFactory.getLogger(DataFetchScheduler.class);

    public DataFetchScheduler() {
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    }

    public static int count = 0;


    @Scheduled(fixedRate = 5000)  // 每5000毫秒执行一次
    public void fetchData() {

        log.info("开始执行涡度数据……");

        String url = "http://localhost:8088/data-query?command=DataQuery&mode=most-recent&format=json&uri=dl:IRR&p1=5";
        try {
            EddyCovarianceData response = restTemplate.getForObject(url, EddyCovarianceData.class);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String rawJson = responseEntity.getBody();  // 原始JSON字符串

            //将接口数据存储在数据库中！
            processDataAndSave(response,rawJson);

        } catch (Exception e) {
            System.err.println("Error fetching or processing data: " + e.getMessage());
        }
    }

    private void printEddyCovarianceData(EddyCovarianceData data) {
        if (data != null && data.getHead() != null && data.getData() != null) {
            System.out.println("Transaction: " + data.getHead().getTransaction());
            System.out.println("Signature: " + data.getHead().getSignature());
            System.out.println("Station Name: " + data.getHead().getEnvironment().getStation_name());

            List<EddyCovarianceData.Field> fields = data.getHead().getFields();
            data.getData().forEach(entry -> {
                System.out.println("Time: " + entry.getTime() + ", No: " + entry.getNo());
                List<Object> vals = entry.getVals();
                for (int i = 0; i < vals.size(); i++) {
                    if (i < fields.size()) {  // Ensure there is a corresponding field for each value
                        System.out.println(fields.get(i).getName() + " (" + fields.get(i).getType() + "): " + vals.get(i) + " (" + fields.get(i).getUnits() + ")");
                    }
                }
            });
        } else {
            System.out.println("No data received or data is incomplete.");
        }
    }

    @Autowired
    private GeoInfoServiceImpl geoInfoServiceImpl;
    @Autowired
    private GeoDetailServiceImpl geoDetailServiceImpl;
    @Autowired
    private GeoTypeServiceImpl geoTypeServiceImpl;

    public void processDataAndSave(EddyCovarianceData data, String rawjson) {
        if (data == null || data.getHead() == null || data.getData() == null) {
            return;
        }

        GeoInfo geoInfo = new GeoInfo();
        // 设置GeoInfo的属性
        geoInfo.setLatitude(22.5726);
        geoInfo.setLongitude(88.3639);
        geoInfo.setAltitude(10.0);
        geoInfo.setStationName(data.getHead().getEnvironment().getStation_name());
        geoInfo.setModel(data.getHead().getEnvironment().getModel());
        geoInfo.setSerialNo(data.getHead().getEnvironment().getSerial_no());
        geoInfo.setOsVersion(data.getHead().getEnvironment().getOs_version());
        geoInfo.setProgName(data.getHead().getEnvironment().getProg_name());
        geoInfo.setTransaction(data.getHead().getTransaction());
        geoInfo.setSignature((long) data.getHead().getSignature());
        geoInfo.setDataJson(rawjson);

        geoInfoServiceImpl.insertGeoInfo(geoInfo);
        int lastInfoId = geoInfoServiceImpl.getLastInsertId();

        data.getData().forEach(entry -> {

            for (int i = 0; i < entry.getVals().size(); i++) {
                if (i >= data.getHead().getFields().size()) {
                    continue;
                }

                String name = data.getHead().getFields().get(i).getName();

//                System.out.println("name"+name);

                //不需要存储message的任何信息，但是后续可能需要检查其值。
                if ("message".equals(name)) {
                    continue;
                }

                String unit = data.getHead().getFields().get(i).getUnits();

                System.out.println("unit"+unit);
//
//                System.out.println("Fields"+data.getHead().getFields().get(i).toString());

                //静态数据里，key-typeid  value-name
                Integer typeId = geoTypeServiceImpl.findTypeIdByName(name);

                //有些查不到的typeId，作为中间数据，将其设置为1
                if (typeId == null) {
                    typeId = 1;
                }

                GeoDetails geoDetails = new GeoDetails();
                geoDetails.setUnits(data.getHead().getFields().get(i).getUnits());
                geoDetails.setGeoInfoId(lastInfoId);
                geoDetails.setTypeId(typeId);
                geoDetails.setName(name);
                geoDetails.setValue(entry.getVals().get(i).toString());

                System.out.println("geoDetails\t\t\t"+geoDetails);
                //善用制表符，适用excel

                //优化策略：批量存储
                geoDetailServiceImpl.saveGeoDetail(geoDetails);
            }
        });
    }

}


